package com.sxz.sbs.module.sale;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.view.View;

import com.nanchen.compresshelper.CompressHelper;
import com.sxz.sbs.R;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.event.EditPhotoEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.photo.PhotoViewerActivity;
import com.sxz.sbs.module.photo.PhotoViewerBean;
import com.sxz.sbs.module.sale.mode.ImgBackBean;
import com.sxz.sbs.module.sale.presenter.EditPhotoPresenter;
import com.sxz.sbs.module.sale.view.EditPhotoView;
import com.sxz.sbs.other.FileBean;
import com.sxz.sbs.other.ImageShowAdapter;
import com.sxz.sbs.view.SelfAdaptionGridView;
import com.sxz.sbs.widget.CommonTitle;
import com.tian.photopicker.PhotoPicker;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class EditPhotoActivity extends BaseActivity<EditPhotoPresenter> implements EditPhotoView {
    @BindView(R.id.photo_grid_view)
    SelfAdaptionGridView gridView;
    private List<FileBean> imgList;
    private ImageShowAdapter adapter;
    private int stallId;
    private int deleteIndex;
    private  List<String> urlList = new ArrayList<>();
    private static final int SELECT_PHOTO_ADD_CAR = 1000;
    private ProgressDialog progressDialog;
    private boolean isDelError;
    @Override
    protected void init() {
        new CommonTitle.Builder(this).setTitle("上传图片").build().show();
        imgList = (List<FileBean>) getIntent().getSerializableExtra("img_list");
        stallId = getIntent().getIntExtra("stall_id",0);
        if (imgList == null) {
            imgList = new ArrayList<>();
        }
        adapter = new ImageShowAdapter(this,imgList,9);
        gridView.setAdapter(adapter);
        adapter.setOnImageShowListener(new ImageShowAdapter.OnImageShowListener() {
            @Override
            public void onImageClick(View v, int position) {
                urlList.clear();
                for (int i = 0; i < imgList.size(); i++) {
                    if (imgList.get(i) != null) {
                        urlList.add(imgList.get(i).getPath());
                    }
                }
                PhotoViewerBean pvb = new PhotoViewerBean(urlList,position) ;
                startActivity(new Intent(EditPhotoActivity.this, PhotoViewerActivity.class)
                        .putExtra(PhotoViewerActivity.PHOTO_VIEWER_TAG, pvb));
            }

            @Override
            public void onImageDelete(View v, int position) {
                deleteIndex = position;
                isDelError = true;
                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("id",imgList.get(position).getId());
                mPresenter.deletePhoto(map);
            }

            @Override
            public void onImageAdd(View v, int position) {
                PhotoPicker.builder().setSelectPhotoCount(9 - (imgList.size() - 1)).
                        start(EditPhotoActivity.this,SELECT_PHOTO_ADD_CAR);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_photo;
    }

    @Override
    protected EditPhotoPresenter createPresenter() {
        return new EditPhotoPresenter();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        List<String> result = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
        progressDialog = ProgressDialog.show(this, null, "上传中...");
        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            if (result.get(i) != null) {
                File newFile = new CompressHelper.Builder(this)
                        .setMaxWidth(720)  // 默认最大宽度为720
                        .setMaxHeight(1080) // 默认最大高度为960
                        .setQuality(60)    // 默认压缩质量为80
                        .setFileName(System.currentTimeMillis()+""+i) // 设置你需要修改的文件名
                        .setCompressFormat(Bitmap.CompressFormat.JPEG) // 设置默认压缩为jpg格式
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .build()
                        .compressToFile(new File(result.get(i)));
                if (newFile != null) {
                    fileList.add(newFile);
                }
            }
        }
        List<MultipartBody.Part> map = filesToMultipartBodyParts(fileList);
        mPresenter.uploadPhoto(stallId,map);
    }

    @Override
    protected void onDestroy() {
        if (imgList.size()< 9) {
            imgList.remove(imgList.size()-1);
        }
        EventBus.getDefault().post(new EditPhotoEvent(imgList));
        super.onDestroy();
    }

    @Override
    public void onUploadPhotoSuccess(List<ImgBackBean> bean) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (mIsLive && bean != null) {
            imgList.remove(imgList.size()-1);
            for (int i = 0; i < bean.size(); i++) {
                imgList.add(new FileBean(bean.get(i).getId(),bean.get(i).getPhotoUrl()));
            }
            adapter.setNotify(imgList);
        }

    }

    @Override
    public void showError(int errorTag, String msg) {
        super.showError(errorTag, msg);
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (isDelError) {
            isDelError = false;
            if (msg.equals("未找到记录")) {
                imgList.remove(deleteIndex);
                adapter.setNotify(imgList);
            }
        }
    }

    @Override
    public void onDeletePhotoSuccess() {
        imgList.remove(deleteIndex);
        adapter.setNotify(imgList);

    }
    public  List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        int i = 1;
        for (File file : files) {
            i++;
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("fileList"+i, file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }
}
